<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;

class WechatController extends Controller
{
    //

    public function server(){
        $wechatApp = new Application(\Config::get('wechat'));
        // 从项目实例中得到服务端应用实例。
        $server = $wechatApp->server;

        $server->setMessageHandler(function ($message) use ($wechatApp) {
            $openid = $message->FromUserName;

            switch ($message->MsgType) {
                case 'text':

                    break;
                case 'image' :
                    return '亲，很抱歉，我还不能识别图片哦~如果想找优惠券，请告诉我您想找的东西的关键词，我这就帮您去找~';
                    break;
                case 'event':
                    switch ($message->Event) {
                        case 'subscribe':
                            break;
                        case 'unsubscribe' :
                            break;
                        case 'SCAN':
                            return "您已关注";
                            break;
                        default:
                            break;
                    }
                    break;
            }
        });
        $response = $server->serve();
        return $response->send();
    }

    //获取微信js sdk
    /**
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          'apis' : str,
     *          'debug' : true/false   //是否开启调试
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' => xxx     返回数据
     *      ]
     *   ]
     */
    //参数1, api参数  2,是否开启调试 3不知道, 4是否返回json格式
    public function getJsSdk(Request $request)
    {
        $apis = $request->input('apis');
        if($apis){
            $apis_arr = explode(',',$apis);
        }else{
            $apis_arr = ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'];
        }

        $wechatConfig = config('wechat');
        $wechatApp = new Application($wechatConfig);

        $js = $wechatApp->js;

        $debug = false;
        if($request->has('debug')){
            $debug = $request->input('debug');
        }

        if($request->has('url')) {
            $js->setUrl($request->get('url'));
        }

        $config = $js->config($apis_arr, $debug, $beta = false, $json = true);
        if(!empty($config)){
            return response()->json(['code'=>1, 'msg'=>'', 'data'=>$config]);
        }else{
            return response()->json(['code'=>0, 'msg'=>'没有数据~', 'data'=>'']);
        }
    }
}
